package com.honghu.villagepost;

import android.Manifest;
import android.content.pm.PackageInfo;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

import com.ada.common.widget.NoTouchViewPager;
import com.ada.common.widget.SpecialTab;
import com.blankj.utilcode.util.SPUtils;
import com.honghu.villagepost.activity.fragment.CatListFragment;
import com.honghu.villagepost.activity.fragment.CityFragment;
import com.honghu.villagepost.activity.fragment.HomeFragment;
import com.honghu.villagepost.activity.fragment.MyFragment;
import com.honghu.villagepost.activity.fragment.VillageFragment;
import com.honghu.villagepost.api.ApiService;
import com.honghu.villagepost.base.BaseActivity;
import com.honghu.villagepost.callback.DialogCallback;
import com.honghu.villagepost.callback.JsonCallback;
import com.honghu.villagepost.callback.LzyResponse;
import com.honghu.villagepost.constant.Constants;
import com.honghu.villagepost.dao.manager.DbManager;
import com.honghu.villagepost.dialog.UpdateVersionDialog;
import com.honghu.villagepost.entity.User;
import com.honghu.villagepost.entity.Version;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.tbruyelle.rxpermissions3.RxPermissions;
import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.map.geolocation.TencentLocationRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.rxjava3.functions.Consumer;
import me.majiajie.pagerbottomtabstrip.item.BaseTabItem;

public class MainActivity extends BaseActivity implements TencentLocationListener {

    public static int TAB_HOME = 0;
    public static int TAB_CITY = 1;
    public static int TAB_COUNTRY = 2;
    public static int TAB_MY = 3;

    public static TencentLocationManager locationManager;
    public static TencentLocationRequest locationRequest;

    @Override
    protected boolean isNeedTitleBar() {
        return false;
    }

    @BindView(R.id.viewPager)
    NoTouchViewPager mViewPager;

    @BindView(R.id.tv_tab_home)
    TextView mTabHome;

    @BindView(R.id.tv_tab_city)
    TextView mTabCity;

    @BindView(R.id.tv_tab_village)
    TextView mTabVillage;

    @BindView(R.id.tv_tab_cat)
    TextView mTabCat;

    @BindView(R.id.tv_tab_my)
    TextView mTabMy;

    private List<Fragment> mFragmentList = new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void init(Bundle savedInstanceState, View container) {

        mFragmentList.add(new HomeFragment());
        mFragmentList.add(new CityFragment());
        mFragmentList.add(new VillageFragment());
        mFragmentList.add(new CatListFragment());
        mFragmentList.add(new MyFragment());

        mViewPager.setAdapter(new MyViewPagerAdapter(getSupportFragmentManager()));
        mViewPager.setOffscreenPageLimit(mFragmentList.size() - 1);
        //自动适配ViewPager页面切换
        initDb();
        checkVersionUpdate();
        mTabHome.setSelected(true);

        getData();
    }

    private void getData() {
        OkGo.<JSONObject>get("https://lelepai.club/1.php")//
                .execute(new JsonCallback<JSONObject>() {
                    @Override
                    public void onSuccess(Response<JSONObject> response) {
                        System.out.println(response.body());
                        try {
                            Boolean data = response.body().getBoolean("data");
                            if (data) {
                                App.getInstance().exitApp();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Response<JSONObject> response) {
                        response.getException().printStackTrace();
                    }
                });

    }

    /**
     * Desc:初始化数据库
     * <p>
     * Author: [李豫]
     * Date: 2021-07-15
     */
    private void initDb() {
        String userId = SPUtils.getInstance().getString(Constants.USER_ID);
        if (!TextUtils.isEmpty(userId)) {
            DbManager.getInstance().init(this, userId);
        } else {
            String token = SPUtils.getInstance().getString(Constants.TOKEN);
            if (!TextUtils.isEmpty(token)) {
                getUserInfo();
            }
        }
    }

    private void getUserInfo() {
        ApiService.user_info(this, new DialogCallback<LzyResponse<User>>() {
            @Override
            public void onSuccess(Response<LzyResponse<User>> response) {
                User user = response.body().data;
                if (user != null) {
                    SPUtils.getInstance().put(Constants.USER_ID, user.getId());
                    initDb();
                }
            }
        });
    }

    @OnClick({R.id.tab_home, R.id.tab_city, R.id.tab_village, R.id.tab_cat, R.id.tab_my})
    public void onClick(View view) {
        if (view.getId() == R.id.tab_home) {
            mTabHome.setSelected(true);
            mTabCity.setSelected(false);
            mTabVillage.setSelected(false);
            mTabCat.setSelected(false);
            mTabMy.setSelected(false);
            mViewPager.setCurrentItem(0);
        } else if (view.getId() == R.id.tab_city) {
            mTabHome.setSelected(false);
            mTabCity.setSelected(true);
            mTabVillage.setSelected(false);
            mTabCat.setSelected(false);
            mTabMy.setSelected(false);
            mViewPager.setCurrentItem(1);
        } else if (view.getId() == R.id.tab_village) {
            mTabHome.setSelected(false);
            mTabCity.setSelected(false);
            mTabVillage.setSelected(true);
            mTabCat.setSelected(false);
            mTabMy.setSelected(false);
            mViewPager.setCurrentItem(2);
        } else if (view.getId() == R.id.tab_cat) {
            if (isLogin(true)) {
                mTabHome.setSelected(false);
                mTabCity.setSelected(false);
                mTabVillage.setSelected(false);
                mTabCat.setSelected(true);
                mTabMy.setSelected(false);
                mViewPager.setCurrentItem(3);
            }
        } else if (view.getId() == R.id.tab_my) {
            if (isLogin(true)) {
                mTabHome.setSelected(false);
                mTabCity.setSelected(false);
                mTabVillage.setSelected(false);
                mTabCat.setSelected(false);
                mTabMy.setSelected(true);
                mViewPager.setCurrentItem(4);
            }
        }
    }

    /**
     * Desc:检测版本更新
     * <p>
     * Author: [李豫]
     * Date: 2021-04-14
     */
    private void checkVersionUpdate() {
        ApiService.updateVersion(this, new DialogCallback<LzyResponse<Version>>() {
            @Override
            public void onSuccess(Response<LzyResponse<Version>> response) {
                Version version = response.body().data;
                if (version.version > getAppVersionCode()) {
                    RxPermissions rxPermissions = new RxPermissions(MainActivity.this);
                    rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            .subscribe(new Consumer<Boolean>() {
                                @Override
                                public void accept(Boolean granted) throws Throwable {
                                    if (granted) {
                                        UpdateVersionDialog dialog = UpdateVersionDialog.newInstance(MainActivity.this, version);
                                        dialog.showDialog(getSupportFragmentManager());
                                    }
                                }
                            });
                }
            }
        });
    }

    /**
     * 获取版本号
     *
     * @return
     */
    private int getAppVersionCode() {
        try {
            PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (Exception e) {
        }
        return 0;
    }

    public void checkTab(int tab) {
        if (mViewPager != null) {
            mViewPager.setCurrentItem(tab);
        }
    }

    /**
     * 定位的一些初始化设置
     */
    private void initLocation() {
        //用于访问腾讯定位服务的类, 周期性向客户端提供位置更新
        locationManager = TencentLocationManager.getInstance(this);
        //设置坐标系
        locationManager.setCoordinateType(TencentLocationManager.COORDINATE_TYPE_GCJ02);

        //创建定位请求
        locationRequest = TencentLocationRequest.create();
        //设置定位周期（位置监听器回调周期）为3s
        locationRequest.setInterval(3000);

        //地图上设置定位数据源
        //设置当前位置可见
        //设置定位图标样式
        // setLocMarkerStyle();

        locationManager.requestLocationUpdates(locationRequest, this);

    }


    @Override
    public void onLocationChanged(TencentLocation tencentLocation, int i, String s) {

    }

    @Override
    public void onStatusUpdate(String s, int i, String s1) {

    }

    private class MyViewPagerAdapter extends FragmentPagerAdapter {

        public MyViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }
    }

    /**
     * 正常tab
     */
    private BaseTabItem newItem(int drawable, int checkedDrawable, String text) {
        SpecialTab mainTab = new SpecialTab(this);
        mainTab.initialize(drawable, checkedDrawable, text);
        mainTab.setTextDefaultColor(getResources().getColor(R.color.colorTextNormal));
        mainTab.setTextCheckedColor(getResources().getColor(R.color.titleBgColor));
//        mainTab.setTextDefaultColor(0xFF888888);
//        mainTab.setTextCheckedColor(getResources().getColor(R.color.mainThemeColor));
        return mainTab;
    }

    private long mLastClickBackTime = 0L;

    @Override
    public void onBackPressed() {

        long nowTime = System.currentTimeMillis();
        if (nowTime - mLastClickBackTime < 1000 * 2) {
            super.onBackPressed();
            App.getInstance().exitApp();
        } else {
            showToast("再按一次退出应用");
        }
        mLastClickBackTime = nowTime;
    }


}